import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'

// 创建axios实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 可以在这里添加token等请求头信息
    const token = localStorage.getItem('token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 处理成功响应
    return response.data
  },
  (error: AxiosError) => {
    // 处理错误响应
    const status = error.response?.status

    // 根据状态码处理不同的错误
    switch (status) {
      case 401:
        // 未授权，可能需要重新登录
        console.error('未授权访问')
        // 可以在这里添加跳转登录页的逻辑
        break
      case 403:
        console.error('权限不足')
        break
      case 404:
        console.error('请求资源不存在')
        break
      case 500:
        console.error('服务器内部错误')
        break
      default:
        console.error('请求失败')
    }

    return Promise.reject(error)
  }
)

// 封装请求方法
const request = {
  get<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
    return instance.get(url, { params, ...config })
  },

  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return instance.post(url, data, config)
  },

  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return instance.put(url, data, config)
  },

  delete<T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
    return instance.delete(url, { params, ...config })
  },

  patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return instance.patch(url, data, config)
  }
}

// 在Nuxt3中注册为插件
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.provide('axios', request)
})

// 类型声明，让TypeScript识别
declare module '#app' {
  interface NuxtApp {
    $axios: typeof request
  }
}

declare module 'vue' {
  interface ComponentCustomProperties {
    $axios: typeof request
  }
}
